<template>
    <div>
        <ul class="nav nav-tabs flex flex-col md:flex-row flex-wrap list-none border-b-0 pl-0 mb-4" id="tabs-tab"
            role="tablist">
            <li class="nav-item" role="presentation">
                <a href="#tabs-about" class="
                    nav-link
                    block
                    font-medium
                    text-xs
                    leading-tight
                    uppercase
                    border-x-0 border-t-0 border-b-2 border-transparent
                    px-6
                    py-3
                    my-2
                    hover:border-transparent hover:bg-gray-100
                    focus:border-transparent
                    active
                    "
                    id="tabs-about-tab"
                    data-bs-toggle="pill"
                    data-bs-target="#tabs-about"
                    role="tab"
                    >Overview</a>
            </li>
            <li class="nav-item" role="presentation">
                <a href="#tabs-homework" class="
                    nav-link block font-medium text-xs
                    leading-tight uppercase
                    border-x-0 border-t-0 border-b-2 border-transparent
                    px-6 py-3 my-2
                    enabled:hover:border-transparent hover:bg-gray-100
                    enabled:focus:border-transparent
                    "
                    :class="{disabled: !allowHomeworkRead}"
                    id="tabs-homework-tab"
                    data-bs-toggle="pill"
                    data-bs-target="#tabs-homework"
                    :data-te-target="allowHomeworkRead?'':'tooltip'"
                    :title="allowHomeworkRead?'':'you need subscribe to see homework'"
                    :disabled="!allowHomeworkRead"
                    role="tab"
                    >Homework</a>
            </li>
        </ul>
        <div class="tab-content" id="tabs-tabContent">
            <div class="tab-pane fade show active divide-y" id="tabs-about" role="tabpanel" >
                <div class="flex justify-auto">
                    <h3 class="text-7xl justify-self-center w-full">{{ courseName }}</h3>
                    <button v-if="subscribeState"
                        class="border rounded m-3 p-2 bg-sky-200"
                        disabled
                    >
                        subscribed&#10004;
                    </button>
                    <button v-else
                        class="border rounded bg-sky-400 m-3 p-2 text-white disabled:bg-sky-200"
                        :data-te-target="allowSubscribe?'':'tooltip'"
                        :title="allowSubscribe?'':'please login first'"
                        :disabled="!allowSubscribe"
                        v-on:click="subscribe"
                    >
                        subscribe
                    </button>
                    <button
                        class="border rounded bg-sky-400 m-3 p-2 text-white disabled:bg-sky-200 disabled:cursor-not-allowed"
                        :data-te-target="allowHomeworkEdit?'':'tooltip'"
                        :title="allowHomeworkEdit?'':'only the teacher create course can edit course info'"
                        :disabled="!allowHomeworkEdit"
                        v-on:click="isPreviewMode=!isPreviewMode"
                    >
                        edit
                    </button>
                </div>
                <div class="m-1 pr-32 pt-5">
                    <v-md-preview v-if="isPreviewMode" :text="courseAbout"></v-md-preview>
                    <mavon-editor
                        v-else
                        v-model="courseAbout"
                        :editable="allowAboutEdit()"
                        @save="saveAbout">
                    </mavon-editor>
                </div>
            </div>
            <div class="tab-pane fade" id="tabs-homework" role="tabpanel" >
                <HomeworkList :courseInfo="courseInfo"></HomeworkList>
            </div>
        </div>
    </div>
</template>

<script>
import HomeworkEditor from './HomeworkEditor.vue';
import HomeworkService from '../services/HomeworkService.js';
import AC from '../accesscontrol.js';
import CourseService from '@/services/CourseService';
import HomeworkList from '@/views/HomeworkList.vue';


export default {
    name: "Course",
    data() {
        return {
            homework: [],
            courseInfo: '',
            courseAbout: '',
            courseName: '',
            courseId: this.$route.params.id,
            isPreviewMode: true,
            subscribeState: false,
        }
    },
    computed: {
        allowHomeworkRead() {
            if(!this.$store.state.user.role) return false;
            const permission1 = AC.can(this.$store.state.user.role).readAny('homework');
            const permission2 = AC.can(this.$store.state.user.role).readOwn('homework');
            return permission1.granted || (permission2.granted && this.subscribeState);
        },
        allowSubscribe() {
            if(!this.$store.state.user.role) return false;
            return true;
        },
        allowHomeworkEdit() {
            if(!this.$store.state.user.role) return false;
            const permission = AC.can(this.$store.state.user.role).updateAny('homework');
            const permission2 = AC.can(this.$store.state.user.role).updateOwn('homework');
            return permission.granted ||
                (permission2.granted && this.courseInfo.creator == this.$store.state.user.id);
        },
    },
    components: {
        HomeworkEditor,
        HomeworkList,
    },
    created() {
        this.getCourseInfo();
        this.getHomework();
        this.isSubscribe();
    },
    methods: {
        async getCourseInfo() {
            const res = await CourseService.getCourse({id: this.$route.params.id});
            console.log('getCourseInfo', res);
            this.courseInfo = res.data;
            this.courseAbout = res.data.about;
            this.courseName = res.data.coursename;
        },
        async getHomework() {
            const res = await HomeworkService.getHomework();
            this.homework = res;
        },
        allowAboutEdit() {
            // TODO only creator of course can change name
            return true;
        },
        async saveAbout() {
            try {
                const res = await CourseService.updateAbout({id: this.$route.params.id, about: this.courseAbout});
                console.log(res);
                this.$message.success("saved");
            } catch(e) {
                console.log("error in saveAbout(): ", e);
            }
        },
        async subscribe() {
            const userId = this.$store.state.user.id;
            if (!userId) {
                this.$message.error("please login first");
                return;
            }
            try {
                const res = await CourseService.subscribe({
                userId: userId,
                courseId: this.courseId,
                });
                this.$message.success("subscribe successfully");
            } catch(e) {
                console.log('in subscribe ', e)
            }
        },
        async isSubscribe() {
            if (!this.$store.state.user.id) {
              this.subscribeState = false;
            } else {
              const res = await CourseService.isSubscribe({
                  courseId: this.courseId,
                  userId: this.$store.state.user.id,
              })
              this.subscribeState = res.data.result ? true : false;
            }
            return this.subscribeState;
        },
    },
}
</script>
